package cloud.mbase.aspect;

import cloud.mbase.dao.ClientInfoDao;
import cloud.mbase.entity.datavo.ClientInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class ClientInfoAspect {

    private final ClientInfoDao clientInfoDao;

    @Autowired
    public ClientInfoAspect(ClientInfoDao clientInfoDao) {
        this.clientInfoDao = clientInfoDao;
    }

    @Pointcut("execution(public * cloud.mbase.controller.*.*(..))")
    public void log() {

    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        ServletRequestAttributes attributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        UsernamePasswordAuthenticationToken token =
                (UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        ClientInfo info = new ClientInfo();
        info.setClientIp(request.getRemoteAddr() + "[" + token.getName() + "]");
        info.setRequestResource(request.getRequestURL().toString());
        clientInfoDao.save(info);
    }

    @After("log()")
    public void after(JoinPoint joinPoint) {
        //System.out.println("after");
    }

    @AfterReturning(returning = "obj", pointcut = "log()")
    public void doAfterReturning(Object obj) {
        //System.out.println("after returning");
    }

    @AfterThrowing(throwing = "ex", pointcut = "log()")
    public void throwss(JoinPoint joinPoint, Exception ex) {
        //System.out.println("throws");
    }
}
